package Team

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_msg "sanguo/protocol/ss/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionJoinTeam struct {
	transaction.TransactionBase
	user *user.User
	req  *codecs.Message
}

func (this *transactionJoinTeam) GetModuleName() string {
	return "Team"
}

func (this *transactionJoinTeam) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionJoinTeam) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionJoinTeam) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionJoinTeam) Begin() {

	node_team, err := cluster.Random("team")
	if nil != err {
		node_game.Debugln("JoinTeam fail : no team server")
		this.user.EndTrans(this)
		return
	}

	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if nil == role || !role.IsRoleModleData() {
		node_game.Debugln(role.GetUserID(), "JoinTeam fail no selected role")
		this.user.EndTrans(this)
		return
	}

	if role.Team != nil {
		node_game.Debugln(role.GetUserID(), role.GetID(), "JoinTeam fail : this.role.Team != nil ")
		this.user.EndTrans(this)
		return
	}

	msg := this.req.GetData().(*cs_message.JoinTeamToS)

	arg := &ss_msg.JoinTeamMsg{
		MsgType: ss_msg.JoinTeamMsgType(ss_msg.JoinTeamMsgType_Join_Apply).Enum(),
		TeamID:  proto.Uint64(msg.GetTeamID()),
		UserID:  proto.String(role.GetUserID()),
		Name:    proto.String(role.GetName()),
		RoleID:  proto.Uint64(role.GetID()),
		Level:   proto.Int32(role.GetLev()),
		Game:    proto.String(node_game.GetSelfService().ToPeerID().ToString()),
	}

	cluster.PostMessage(node_team, arg)
	this.user.EndTrans(this)
}

func (this *transactionJoinTeam) End() {
}

func (this *transactionJoinTeam) Timeout() {
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.JoinTeamToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionJoinTeam{
			user: user,
			req:  msg,
		}
	})
}
